<?php
function cmp($a, $b)
{
	if ($a['sortno'] == $b['sortno']) {
    	return 0;
    }
    return ($a['sortno'] < $b['sortno']) ? -1 : 1;
}
	
class SearchController extends ZendX_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }
	
	public function supplierAction($keyword='*', $from=0, $size=10)
	{
		$svc = new App_Service_Jsonp();
		$cli = $this->esClient("supplier");
		
		$keyword = $this->toDBC($keyword);
		
		if (empty($keyword) || ctype_space($keyword)) {
			$keyword = "*";
		}
		
		$querydata = array(
			"from" => $from,
			"size" => $size,
			"fields" => array("_id", "name"),
			"query" => array(
				"filtered" => array(
					"query" => array(
						"query_string" => array(
							"fields" => array("name"),
							"query" => $keyword,
							"default_operator" => "AND"
						)
					),
					"filter" => array(
						"match_all" => new stdClass()
					)
				)
			),
			"sort" => array(
				array("update_at" => "desc")
			)
		);
		$res = $cli->search($querydata);
		echo $_GET["jsonpcallback"].'('.$svc->JSON(array('result' => $res)).')';
		exit();
	}
	
	public function productAction($keyword='*', $from=0, $size=10, $top='', $leaf='', $brand='', $order='', $propvalues='', $kwName='', $kwBrand='', $kwSpec='', $kwSupplier='', $kwlPrice='', $kwhPrice='', $kwDay='')
	{
		
		
		$filter = array();
		$sort = array();
		$facets = array();		
		$svc = new App_Service_Jsonp();
		$cli = $this->esClient("product");
		
		$keyword = $this->toDBC($keyword);
		$kwName = $this->toDBC($kwName);
		$kwBrand = $this->toDBC($kwBrand);
		$kwSpec = $this->toDBC($kwSpec);
		$fields = array('_id', 'name', 'offertime', 'series', 'remark', 'supplier', 'brand');
		
		$auth = Zend_Auth::getInstance();
		if ($auth->hasIdentity()) {
			$fields = array('_id', 'name', 'price', 'offertime', 'series', 'remark', 'supplier', 'brand');
		}
		
		
		if (empty($keyword) || ctype_space($keyword)) {
			$keyword = "*";
		}
		
		if (!empty($kwName) && !ctype_space($kwName)) {
			$keyword .= " " . "name:" . "\"" . $kwName . "\"" . " ";
		}
		
		if (!empty($kwBrand) && !ctype_space($kwBrand)) {
			$keyword .= " " . "brand:" . "\"" . $kwBrand . "\"" . " ";
		}
		
		if (!empty($kwSpec) && !ctype_space($kwSpec)) {
			$keyword .= " " . "properties.value:" . "\"" . $kwSpec . "\"" . " ";
		}
		
		if (!empty($kwSupplier) && !ctype_space($kwSupplier)) {
			$keyword .= " " . "supplier:" . "\"" . $kwSupplier . "\"" . " ";
		}

		if (!empty($top)) {
			$filter["and"][] = array("term" => array("category.top.untouched" => $top));
	
			$facets = array(
				"leafcategory" => array(
					"terms" => array(
						"field" => "category.leaf.untouched",
						"size" => 100
					)
				)
			);
		}
		
		if (!empty($leaf)) {
			$filter["and"][] = array("term" => array("category.leaf.untouched" => $leaf));
			
			$facets = array(
				"propvalue" => array(
					"terms" => array(
						"script_field" => "_source.properties",
						"size" => 200
					)
				),
				"brand" => array(
					"terms" => array(
						"field" => "brand.untouched",
						"size" => 100
					)
				)
			);
		}
		
		if (!empty($brand)) {
			$filter["and"][] = array("term" => array("brand.untouched" => $brand));
			if (key_exists('brand', $facets)) {
				unset($facets["brand"]);
			}
		}
		
		$props = array();
		if (!empty($propvalues)) {		
			$ePropvalues = explode(';', $propvalues);
			foreach ($ePropvalues as $v) {
				if (empty($v)) {
					continue;
				}
				$ePropvalue = explode(':', $v);
				$name = $ePropvalue[0];
				$value = $ePropvalue[1]; 
				$props[]=$name;
				$filter["and"][] = array(
					"bool" => array(
						"must" => array(
								array("term" => array("properties.name.untouched" => $name)),
								array("term" => array("properties.value.untouched" => $value))
							)
						)
				);
			}
			
			//$filter["and"][] = array("terms" => array("properties.value.untouched" => $propvalues));
//			foreach ($propvalues as $v) {
//				$filter["and"][] = array("term" => array("properties.value" => $v));
//			};
		}
		
		if (!empty($kwlPrice) || !empty($kwhPrice)) {
			if (empty($kwlPrice['lPrice'])) {
				$kwlPrice['lPrice'] = (float)0;
			}
			else {
				$kwlPrice['lPrice'] = (float)$kwlPrice['lPrice'];
			}
			
			if (empty($kwhPrice['hPrice'])) {
				$kwhPrice['hPrice'] = 1.8e308;
			}
			else {
				$kwhPrice['hPrice'] = (float)$kwhPrice['hPrice'];
			}
			
			$filter["and"][] = array(
				"range" => array(
					"price" => array(
						"from" => $kwlPrice,
						"to" => $kwhPrice 
						)
					)
			);
		}
		
		if (!empty($kwDay)) {
			$kwDay = '-' . $kwDay . ' day';
			$date = date("Y-m-d",strtotime($kwDay));
			
			$filter["and"][] = array(
				"range" => array(
					"price" => array(
						"gte" => $date
						)
					)
			);
		}
		
		if (!empty($order)) {
			$explodes = explode(' ', $order);
			if (count($explodes) == 2) {
				$sort = array(
					array($explodes[0] => $explodes[1]),
					"_score"
				);
			}
		}
		
		
		if (empty($filter)) {
			$filter = array(
				"match_all" => new stdClass()
			);
		}
		
		if (empty($sort)) {
			$sort = array("_score");
		}
		
		if (empty($facets)) {
			$facets = array(
				"topcategory" => array(
					"terms" => array(
						"field" => "category.top.untouched",
						"size" => 100
					)
				)
			);
		}
		
		$querydata = array(
			"from" => $from,
			"size" => $size,
			"fields" => $fields,
			"query" => array(
				"filtered" => array(
					"query" => array(
						"query_string" => array(
							"fields" => array("name", "properties.value", "brand", "supplier", "series"),
							"query" => $keyword,
							"default_operator" => "AND"
						)
					),
					"filter" => $filter
				)
			),
			"sort" => $sort,
			"facets" => $facets
		);
		$res = $cli->search($querydata);
				
		$rFacets = $res['facets'];
		if (key_exists('propvalue', $rFacets)) 
		{
			$terms = $rFacets['propvalue']['terms'];
			$sPropValue = array();
			foreach ($terms as $v) {
				$term = substr($v['term'], 1, strlen($v['term'])-2);
				$eTerm = explode(',', $term);
				$eName = explode('=', $eTerm[0]);
				$eValue = explode('=', $eTerm[1]);
				if (in_array($eName[1], $props)) {
					continue;
				}
				$sPropValue[$eName[1]][$eValue[1]] = $v['count'];
			}
			
			
			
			
			$res['facets']['propvalue'] = array();
			$client = $this->couchClient();
			$dbRes = $client->asArray()->reduce(false)->key(array($top, $leaf))->getView("services", "getCategoryPropValue");
			if (count($dbRes['rows']) == 1) {
				$dbPropvalue = $dbRes['rows'][0]['value']['properties'];
				
				//属性排序
				usort($dbPropvalue, 'cmp');	
				
				$propvalue = array();
				foreach ($dbPropvalue as $kPV => $vPV) {
					//属性值排序
					usort($dbPropvalue[$kPV]['values'], 'cmp');

					$values = array();
					foreach ($dbPropvalue[$kPV]['values'] as $k => $v) {
						
						$count = null;
						if (key_exists($dbPropvalue[$kPV]['name'], $sPropValue)) {
							if (key_exists($v['value'], $sPropValue[$dbPropvalue[$kPV]['name']])) {
								$count = $sPropValue[$dbPropvalue[$kPV]['name']][$v['value']];
							}
						}
						
						if (!is_null($count)) {
							$dbPropvalue[$kPV]['values'][$k]['count'] = $count;
							$values[] = $dbPropvalue[$kPV]['values'][$k];
						}
					}
		
					$dbPropvalue[$kPV]['values'] = $values;
					
					if (!empty($dbPropvalue[$kPV]['values'])) {
						$propvalue[]=$dbPropvalue[$kPV];
					}
				}

				$res['facets']['propvalue'] = $propvalue;
			}
		}
		
		echo $_GET["jsonpcallback"].'('.$svc->JSON(array('result' => $res)).')';
		exit();
	}
	
	public function supplierproductAction($supplier='', $from=0, $size=10, $order='', $brand='', $name='', $spec='')
	{
		$svc = new App_Service_Jsonp();
		$cli = $this->esClient("product");

		$supplier = $this->toDBC($supplier);
		$name = $this->toDBC($name);
		$spec = $this->toDBC($spec);
		
		$keyword = "";
		$filter = array();		
		$sort = array();
		$facets = array();
		$fields = array('_id', 'name', 'offertime', 'series', 'remark', 'supplier', 'brand');
		
		$auth = Zend_Auth::getInstance();
		if ($auth->hasIdentity()) {
			$fields = array('_id', 'name', 'price', 'offertime', 'series', 'remark', 'supplier', 'brand');
		}
		
		if (!empty($name) && !ctype_space($name)) {
			$keyword .= "name:" . "\"" . $name . "\"" . " ";
		}
		
		if (!empty($spec) && !ctype_space($spec)) {
			$keyword .= "properties.value:" . "\"" . $name . "\"" . " ";
		}
		
		$filter["and"][] = array("term" => array("supplier.untouched" => $supplier));
		
		if (!empty($brand)) {
			$filter["and"][] = array("term" => array("brand.untouched" => $brand));
		}
		
		if (!empty($order)) {
			$explodes = explode(' ', $order);
			if (count($explodes) == 2) {
				$sort = array(
					array($explodes[0] => $explodes[1]),
					"_score"
				);
			}
		}
		
		
		if (empty($keyword)) {
			$keyword = "*";
		}
		
		if (empty($sort)) {
			$sort = array("_score");
		}
		
		if (empty($facets) && empty($brand)) {
			$facets = array(
				"brand" => array(
					"terms" => array(
						"field" => "brand.untouched",
						"size" => 100
					)
				)
			);
		}
			
		$querydata = array(
			"from" => $from,
			"size" => $size,
			"query" => array(
				"filtered" => array(
					"query" => array(
						"query_string" => array(
							"query" => $keyword,
							"default_operator" => "AND"
						)
					),
					"filter" => $filter
				)
			),
			"sort" => $sort,
			"facets" => $facets
		);
		$res = $cli->search($querydata);
		echo $_GET["jsonpcallback"].'('.$svc->JSON(array('result' => $res)).')';
	}
}